package de.hsowl.tod4a.global.crypto;

import java.security.MessageDigest;
/**
 * Basic MD5-Hash interface
 * @author Sebastian Witt
 *
 */
public class Message_Digest {

	/**
	 * Hashes a String with MD5.
	 * @param toHash
	 * @return
	 * @throws Exception
	 */
	public static String getMD5(String toHash) throws Exception {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(toHash.getBytes());
			byte messageDigest[] = md5.digest();

			return CryptoUnit.toHex(messageDigest);

		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * Hashes a String with MD5 'rounds' time.
	 * @param toHash
	 * @param rounds
	 * @return
	 * @throws Exception
	 */
	public static String getMD5(String toHash, int rounds) throws Exception {

		if ((toHash == null) || (rounds < 1)) {
			return null;
		}

		String ret = toHash;
		toHash = null;
		for (int i = 0; i < rounds; i++) {
			if (ret == null) {
				return null;
			}
			ret = getMD5(ret);
		}
		return ret;
	}
}
